<template>
  <div class="dialog-wrap">
    <el-dialog :visible.sync="dialogVisible.show" center>
      <div class="show-title">角色名称：{{role_name}}</div>
      <el-input
        prefix-icon="el-icon-search"
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        style="margin-bottom: 10px;"
        clearable
      ></el-input>
      <div class="btn-group">
        <el-button type="primary" plain size="small" style="margin-right: 10px;" @click="fnAll">全选</el-button>
        <el-button type="success" plain size="small" style="margin-right: 10px;" @click="fnOther">反选</el-button>
        <el-button type="warning" plain size="small" style="margin-right: 10px;" @click="fnClear">清空</el-button>
        <el-button type="primary" size="small" @click="fnSubmit">
          提交
          <i class="el-icon-upload2 el-icon--right"></i>
        </el-button>
      </div>

      <el-tree
        ref="tree"
        :data="initData"
        :checked="checked"
        show-checkbox
        node-key="id"
        :filter-node-method="filterNode"
        :default-expanded-keys="expanded"
        :default-checked-keys="checked"
        :props="defaultProps"
        @check="currentChecked"
        @all="fnAll"
        @other="fnOther"
      ></el-tree>
    </el-dialog>
  </div>
</template>

<script>
import { getData, postData } from "@/request/http";
export default {
  name: "audit",
  props: {
    dialogVisible: {
      type: Object,
      default() {
        return {
          show: false
        };
      }
    },
    role_id: {
      type: String,
      default: ""
    },
    role_name: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      role_id_seled: "", //  父组件的角色id
      role_name_seled: "", //  父组件的角色name
      filterText: "", //搜索
      defaultProps: {
        children: "children",
        label: "label"
      },
      arr: [],
      checkArr: [],
      otherArr: [],
      checked: [5], // 默认选中数据
      expanded: [2, 3], // 默认展开数据
      initData: [], // 树形数据（数据严格按照这个模式传）
      checkedKeys: [], // 选中的key
      firstArr: [] // 一级id
    };
  },
  mounted() {
    this.firstArr = [];
    this.arr = [];
    this.otherArr = [];
    this.checkArr = this.checked;
    this.checkedKeys = [];
  },
  watch: {
    //搜索过滤
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    role_id: {
      handler(newVal) {
        this.role_id_seled = newVal;
       // console.log(this.role_id_seled);
        this.getList();
      },
      immediate: true
    },
    role_name: {
      handler(newVal) {
        this.role_name_seled = newVal;
       // console.log(this.role_name_seled);
      },
      immediate: true
    }
  },
  methods: {
    //提交
    fnSubmit() {
      var that = this;
      console.log(that.checkedKeys);
      var result = that.checkedKeys.filter(item => {
        return that.firstArr.indexOf(item) == -1;
      });
      if (result == 0) {
        that
          .$confirm("一个都没勾选,该角色将没有任何权限, 是否继续?", "授权API", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            that.submit(result);
          })
          .catch(() => {
            that.$message.success("已取消");
          });
      } else {
        that.submit(result);
      }
     // that.submit(result);
    },
    submit(result) {
      var that = this;
      postData("/adminweb/role/api/set", {
        role_id: that.role_id_seled,
        apis: result
      })
        .then(res => {
          if (res.code == 0) {
            that.$message.success("授权成功！");
            that.$emit("success", true);
          } else {
            that.$message.error(res.code + "，" + res.msg);
          }
        })
        .catch(res => {
          that.$message.error(res.code + "，" + res.msg);
        });
    },
    //转换
    getDatas(datas, arr, key) {
      if (datas.length > 0) {
        for (let i = 0; i < datas.length; i++) {
          let item = {};
          item.children = [];
          item.id = datas[i][key + "_name"];
          item.label = datas[i][key + "_desc"];
          arr.push(item);
          if (key == "sort") {
            this.firstArr.push(item.id);
          }
          if (datas[i].apis && datas[i].apis.length > 0) {
            this.getDatas(datas[i]["apis"], item.children, "api");
          }
        }
      }
    },
    //初始列表数据
    getList() {
      this.checked = [];
      postData("/adminweb/api/list", {
        status: 0,
        sort_name: "all",
        auth_for: "role",
        auth_for_id: this.role_id_seled,
        with_details: 0
      })
        .then(res => {
          if (res.code == 0) {
            var arr = [];
            let sorts = res.datas.sorts;
           // console.log(sorts);
            //初始的时候，根据authorized，勾选上
            for (var i = 0; i < sorts.length; i++) {
              var apis = sorts[i].apis;
              for (var j = 0; j < apis.length; j++) {
                if (apis[j].authorized == 1) {
                  this.checked.push(apis[j].api_name);
                }
              }
            }
            this.getDatas(sorts, arr, "sort");
            this.initData = arr;
          }else if (res.code == -56055) {
            return;
          }  else {
           this.$message.error(res.code + "，" + res.msg);
          }
        })
        .catch(res => {
          this.$message.error(res.code + "，" + res.msg);
        });
    },

    comAll(arr) {
      if (Array.isArray(arr) && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          this.arr.push(arr[i]["id"]);
          var children = arr[i]["children"];
          if (Array.isArray(children) && children.length > 0) {
            this.comAll(children);
          }
        }
      }
    },

    comOther(arr) {
      if (Array.isArray(arr) && arr.length > 0) {
        var halfCheck = this.$refs.tree.getHalfCheckedKeys();
        this.checkArr = Array.from(new Set([...this.checkArr, ...halfCheck]));
        for (let i = 0; i < arr.length; i++) {
          if (this.checkArr.indexOf(arr[i]["id"]) == -1) {
            this.otherArr.push(arr[i]["id"]);
          }
          var children = arr[i]["children"];
          if (Array.isArray(children) && children.length > 0) {
            this.comOther(children);
          }
        }
      }
    },
    //全选
    fnAll() {
      this.arr = [];
      this.comAll(this.initData);
      this.checkArr = Array.from(new Set(this.arr));
      this.arr = Array.from(new Set(this.arr));
      this.$refs.tree.setCheckedKeys(this.arr);
      this.checkedKeys = this.$refs.tree.getCheckedKeys();
      this.$emit("all", this.$refs.tree.getCheckedKeys());
    },
    //反选
    fnOther() {
      this.otherArr = [];
      this.comAll(this.initData);
      if (this.arr.length > 0 && this.checkArr.length > 0) {
        this.comOther(this.initData);
      } else if (this.arr.length > 0 && this.checkArr.length == 0) {
        this.otherArr = Array.from(new Set(this.arr));
      }
      this.checkArr = this.otherArr;
      this.$refs.tree.setCheckedKeys(this.otherArr);
      this.checkedKeys = this.$refs.tree.getCheckedKeys();
      this.$emit("other", this.$refs.tree.getCheckedKeys());
    },
    //清空
    fnClear() {
      this.arr = [];
      this.otherArr = [];
      this.checkArr = [];
      this.$refs.tree.setCheckedKeys([]);
      this.checkedKeys = [];
      this.$emit("clear", []);
    },
    currentChecked() {
      this.checkArr = this.$refs.tree.getCheckedKeys();
      this.checkedKeys = this.$refs.tree.getCheckedKeys();
      this.$emit("check", this.$refs.tree.getCheckedKeys());
    },
    //搜索过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    }
  }
};
</script>

<style scoped>
.dialog-wrap >>> .el-dialog {
  height: 600px;
  overflow-y: scroll;
}
.btn-group {
  margin: 10px 0;
}
.show-title {
  margin-bottom: 10px;
  font-weight: 600;
}
</style>
